package com.ck567.springbootnettyprotobufjava.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.ResourceLeakDetector;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.InetSocketAddress;

/**
 * @description: 通信server
 */
@Component
@Slf4j
public class  MessageServer {

    private final EventLoopGroup BOSS = new NioEventLoopGroup();

    private final EventLoopGroup WORKER = new NioEventLoopGroup();

    private final MessageServerHandlerInitializer messageServerHandlerInitializer;

//    @Value("${netty.server.port}")
    private Integer serverPort = 8011;

    private Channel channel;

    @Autowired
    public MessageServer(MessageServerHandlerInitializer messageServerHandlerInitializer) {
        this.messageServerHandlerInitializer = messageServerHandlerInitializer;
    }

    /**
     * @description: 场景服务端启动
     */
    @PostConstruct
    public void start() throws InterruptedException {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(BOSS, WORKER)
                // 指定Channel
                .channel(NioServerSocketChannel.class)

                // 使用指定服务端口
                .localAddress(new InetSocketAddress(serverPort))

                // 服务端可连接队列数,对应TCP/IP协议listen函数中backlog参数
                .option(ChannelOption.SO_BACKLOG, 1024)

                // 设置TCP长连接
                .childOption(ChannelOption.SO_KEEPALIVE, true)

                // 将小的数据包包装成更大的帧进行传送，提高网络的负载
                .childOption(ChannelOption.TCP_NODELAY, true)

                // 初始化通信协议并进行业务逻辑处理
                .childHandler(messageServerHandlerInitializer);
        //  JVM
        ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.ADVANCED);
        ChannelFuture future = bootstrap.bind().sync();
        if (future.isSuccess()) {
            channel = future.channel();
            log.info("im-server started");
        }
    }

    /**
     * @description: 场景服务端销毁
     */
    @PreDestroy
    public void destroy() throws InterruptedException {
        if (channel != null) {
            channel.close();
        }
        BOSS.shutdownGracefully().sync();
        WORKER.shutdownGracefully().sync();
        log.info("im-server shutdown");
    }

}
